/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.service;

import br.com.foxline.enums.TypePatio;
import br.com.foxline.model.Bairro;
import br.com.foxline.model.City;
import br.com.foxline.model.Dne;
import br.com.foxline.model.Endereco;
import br.com.foxline.util.Caracter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

/**
 *
 * @author laverson
 */
@Stateless
public class DneService extends GenericService<Dne> {

    @EJB
    CityService cityService;
    @EJB
    BairroService bairroService;

    public DneService() {
        super(Dne.class);
    }

    @Override
    public void save(Dne entity) {
        entity.setCep(Caracter.removecaracter(entity.getCep()));
        entity.setUpdateAt(new Date());
        entity.setAtivo(true);
//        entity = fillFilds(entity);
        super.save(entity);
    }

    @Override
    public void delete(Dne entity) {
        entity.setUpdateAt(new Date());
        entity.setAtivo(false);
        update(entity);
    }
    @Override
    public void update(Dne entity) {
        entity.setCep(Caracter.removecaracter(entity.getCep()));
//        entity = fillFilds(entity);
        entity.setUpdateAt(new Date());
        super.update(entity);
    }

    private Dne fillFilds(Dne entity) {
        entity.setCep(Caracter.removecaracter(entity.getCep()));

        entity.setNomeclog(entity.getPatio());

        for (TypePatio type : Arrays.asList(TypePatio.values())) {
            if (entity.getPatio().toLowerCase().trim().startsWith(type.getName().toLowerCase())) {
                entity.setNomeslog(entity.getPatio().trim().substring(type.getName().length() + 1));
            }
        }

        return entity;
    }

    public Endereco existCep(Endereco a) {
        a.setCep(Caracter.removecaracter(a.getCep()));

        Dne dne;
        String sql = "Select d from Dne d where d.cep like lower(:cep)";

        Query query = getEntityManager().createQuery(sql);
        query.setParameter("cep", a.getCep());
        try {
            dne = (Dne) query.getResultList().get(0);

        } catch (NoResultException nr) {
            return null;
        } catch (NonUniqueResultException nre) {
            return null;
        } catch (Exception e) {
            return null;
        }

        return dne != null ? dneToEndereco(dne) : null;
    }

    private Endereco dneToEndereco(Dne dne) {
        Endereco address = new Endereco();

        address.setCep(Caracter.removecaracter(dne.getCep()));
        address.setBairro(dne.getDistrict());
        address.setLogradouro(dne.getPatio());
        address.setNomeclog(dne.getNomeclog());
        address.setNomeslog(dne.getNomeslog());

        if (dne.getBairro() != null || dne.getBairro().getId() != null) {
            address.setBairroDne(dne.getBairro());
            address.setBairro(dne.getBairro().getNome());
            address.setUf(dne.getBairro().getUf());
        }

        if (dne.getCity() != null || dne.getCity().getId() != null) {
            if (dne.getCity().getCountry() != null || dne.getCity().getCountry().getId() != null) {
                address.setMunicipio(dne.getCity().getCountry().getName());
            }
        }

        return address;
    }

    /**
     *
     * @param findDne pesquisa
     */
    public List<Dne> findDne(Dne dne) {
        dne.setCep(Caracter.removecaracter(dne.getCep()));
        dne.setPatio(dne.getPatio().replace(" ", "%"));

        City city = dne.getCity();
        Bairro bairro = dne.getBairro();

        String sql = "select d from Dne d ";

        if ((city != null)) {
            if (city.getId() != null) {
                city = cityService.find(city.getId());
                if ((city.getName() != null) && (!city.getName().equals(""))) {
                    sql += "JOIN d.city c ";
                }
            }
        }
        if (bairro != null) {
            if (bairro.getId() != null) {
                bairro = bairroService.find(bairro.getId());
                if ((bairro.getNome() != null) && (!bairro.getNome().equals(""))) {
                    sql += "JOIN d.bairro b ";
                }
            }
        }

        sql += " WHERE ";

        if ((dne.getCep() != null) && (!dne.getCep().equals(""))) {
            sql += " lower(d.cep) like lower(:cep) and ";
        }
        if ((dne.getPatio() != null) && (!dne.getPatio().equals(""))) {
            sql += " lower(d.patio) like lower(:patio) and ";
        }
        if (city != null) {
            if ((city.getName() != null) && (!city.getName().equals(""))) {
                sql += " lower(c.name) like lower(:nameCity) and ";
            }
        }
        if (bairro != null) {
            if ((bairro.getNome() != null) && (!bairro.getNome().equals(""))) {
                sql += " lower(b.nome) like lower(:nomeBairro) and ";
            }
        }

        sql += " d.ativo = true and 1=1 ";
        Query query = getEntityManager().createQuery(sql);

        if ((dne.getCep() != null) && (!dne.getCep().equals(""))) {
            query.setParameter("cep", "%" + dne.getCep() + "%");
        }
        if ((dne.getPatio() != null) && (!dne.getPatio().equals(""))) {
            query.setParameter("patio", "%" + dne.getPatio() + "%");
        }
        if ((city != null)) {
            if ((city.getName() != null) && (!city.getName().equals(""))) {
                query.setParameter("nameCity", "%" + "parnaíba" + "%");
            }
        }
        if ((bairro != null)) {
            if ((bairro.getNome() != null) && (!bairro.getNome().equals(""))) {
                query.setParameter("nomeBairro", "%" + bairro.getNome() + "%");
            }
        }

        return query.getResultList();
    }

    public List<String> getAllBairro() {
        String sql = "Select b.nome from Dne d JOIN d.city c JOIN d.bairro b where "
                + " c.id = :city";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("city", 5658);
        System.err.println((List<String>) query.getResultList());
        return (List<String>) query.getResultList();
    }

    public List<Dne> getAllUpdate(Date date) {
        System.err.println(date);
        String sql = "Select d from Dne d where d.updateAt > :update";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("update", date);

        return (List<Dne>) query.getResultList();
    }
}
